<?php

/**
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/17 19:20
 */

namespace App\Services\Web;

use App\Http\Format\FormatBase;
use App\Models\SysMessageModel;
use App\Models\SysPermissionsModel;
use App\Models\SysRoleModel;
use App\Models\SysRolePermissionsModel;
use App\Models\SysUserModel;
use App\Models\UserTokenModel;
use App\Models\SysUserRoleModel;
use App\Services\CommonService;
use Exception;

class UserService extends CommonService
{
    /**
     * 新增/修改用户信息
     * @param $params
     * @return array
     */
    public function homepageUpdateWhole($params): array
    {
        //判断账号，工号，昵称去重
        //id存在，修改，排除查找
        $whereNotId = [];
        if (!empty($params['id'])) {
            $whereNotId = [$params['id']];
        }

        //手机号不能重复
        $whereOrOne = 0;
        if (!empty($params['mobile'])) {
            $whereOrOne = $params['mobile'];
        }

        //昵称不能重复
        $whereOrTwo = 0;
        if (!empty($params['nickname'])) {
            $whereOrTwo = $params['nickname'];
        }

        //员工工号不能重复
        $whereOrThree = 0;
        if (!empty($params['job_num'])) {
            $whereOrThree = $params['job_num'];
        }

        $userTran = SysUserModel::getOneByDeWeight($whereNotId, $whereOrOne, $whereOrTwo, $whereOrThree);

        if (!empty($userTran)) {
            return [1002, '手机号/昵称/员工工号，重复！'];

        }

        $this->beginTransaction();

        try {
            if (empty($params['id'])) {
                //新增
                $userId = UserService::getInstance()->homepageAdd($params);

                //添加token
                UserTokenModel::insertSingle([
                    'token' => md5($userId . time()),
                    'user_id' => $userId,
                    'status' => 3,
                    'created_at' => time(),
                    'expired_at' => time() + (86400 * 7),
                ]);

            } else {
                //数据库操作
                UserService::getInstance()->homepageUpdate($params);
            }


            $this->commit();

        } catch (Exception $e) {
            $this->rollback();

            return [1023, '入库失败'];
        }

        return [];
    }

    /**
     * 修改用户信息
     * @param $params
     * @return array
     */
    public function homepageUpdate($params): array
    {
        //id赋值
        $id = $params['id'] ?? 0;

        //修改角色
        if (!empty($params['role_id'])) {
            SysUserRoleModel::deleteUserRole(['uid' => $id]);
            SysUserRoleModel::insertUserRole(['uid' => $id, 'role_id' => $params['role_id']]);
        }

        //修改用户


        //处理传参，进行修改
        $insertUser = $this->handleUserUpdate($params);

        if (!empty($insertUser)) {
            SysUserModel::updateSingle(['id' => $id], $insertUser);

        }

        return [];
    }

    /**
     * 新增用户信息
     * @param $params
     * @return int
     */
    public function homepageAdd($params): int
    {
        $userId = 0;

        //处理传参，进行新增
        $insertUser = $this->handleUserUpdate($params);
        if (!empty($insertUser)) {
            $userId = SysUserModel::insertSingle($insertUser);

        }

        //新增角色和用户关系
        if (!empty($params['role_id']) && !empty($userId)) {
            SysUserRoleModel::insertUserRole(['uid' => $userId, 'role_id' => $params['role_id']]);
        }

        return $userId;
    }

    /**
     * 修改用户信息
     * @param $params
     * @return array
     */
    public function handleUserUpdate($params): array
    {
        $data = [];
        if (!empty($params['sex'])) {
            $data['sex'] = $params['sex'];
        }

        if (!empty($params['mobile'])) {
            $data['mobile'] = $params['mobile'];
        }

        if (!empty($params['email'])) {
            $data['email'] = $params['email'];
        }

        if (!empty($params['nickname'])) {
            $data['nickname'] = $params['nickname'];
        }

        if (!empty($params['account'])) {
            $data['account'] = $params['account'];
        }

        if (!empty($params['password'])) {
            $data['password'] = md5($params['password']);
        }

        if (!empty($params['job_num'])) {
            $data['job_num'] = $params['job_num'];
        }

        if (!empty($params['desc'])) {
            $data['desc'] = $params['desc'];
        }

        if (!empty($params['area_province_id'])) {
            $data['area_province_id'] = $params['area_province_id'];
        }

        if (!empty($params['area_city_id'])) {
            $data['area_city_id'] = $params['area_city_id'];
        }

        if (!empty($params['area_district_id'])) {
            $data['area_district_id'] = $params['area_district_id'];
        }

        if (!empty($params['wx_num'])) {
            $data['wx_num'] = $params['wx_num'];
        }

        if (!empty($params['wx_qcode'])) {
            $data['wx_qcode'] = $params['wx_qcode'];
        }

        return $data;
    }

    /**
     * 获取状态正常的用
     */
    public function roleAll(array $data = []): array
    {
        $where = array();
        $where[] = ['deleted_at', '=', 0];
        //过滤删选条件-状态
        if (isset($data['status']) && ($data['status'] == '1' || $data['status'] == '0')) {
            $where[] = ['status', '=', $data['status']];
        }

        //过滤删选条件-juese名称
        if (isset($data['role_name']) && !empty($data['role_name'])) {
            $where[] = ['role_name', 'like', '%' . $data['role_name'] . '%'];
        }

        $query = SysRoleModel::query()
            ->with('permissionId')
            ->with('user');

        $query->where($where);

        //过滤删选条件-创建时间
        if (isset($data['created_at']) && $data['created_at']) {
            $created_at = explode(' - ', $data['created_at']);
            $query->whereBetween('created_at', [strtotime($created_at[0]), strtotime($created_at[1]) + 86400]);
        }

        $list = $query->paginate(request()->get('limit', 30));
        $list = $list ? $list->toArray() : [];

        foreach ($list['data'] as &$value) {
            //权限不为空
            if (!empty($value['permission_id'])) {
                $value['permission_id'] = array_column($value['permission_id'], 'permission_id');
            }

            $value['user_num'] = 0;
            if (!empty($value['user'])) {
                $value['user_num'] = count($value['user']);
            }

            unset($value['user']);
        }
        return FormatBase::listData($list);

    }

    /**
     * 获取用户信息
     * @param array $sysUserOne
     * @return array
     */
    public function getUserInfo(array $sysUserOne = []): array
    {
        //获取角色
        $roleAll = SysUserRoleModel::getDataOne(['uid' => $sysUserOne['id']]);

        //获取当前角色的有权限的菜单
        $menuList = SysRolePermissionsModel::userRoleAll('rp.role_id', array_column($roleAll, 'role_id'));
        //处理菜单，按钮等数据
        //菜单
        $menuInfo = [];

        //按钮权限集合
        $buttonInfo = [];

        foreach ($menuList as $value) {
            $value['meta']['title'] = $value['title'];
            $value['meta']['icon'] = $value['icon'];

            unset($value['title'], $value['icon']);

            if ($value['type'] == 2) {
                $buttonInfo[] = $value;
            }
            if ($value['type'] == 1) {
                $menuInfo[] = $value;
            }
        }

        foreach ($menuInfo as &$menu) {
            $menu['auth'] = [];
            foreach ($buttonInfo as $button) {
                if ($button['parent_id'] == $menu['id']) {
                    $menu['auth'][] = $button;
                }
            }
        }

        $menuInfo = makeTree($menuInfo, 'id', 'parent_id', 'children');
        $userAuth = array_column($menuList, 'tag');

        return [
            'id' => $sysUserOne['id'],
            'wx_num' => $sysUserOne['wx_num'],
            'wx_qcode' => $sysUserOne['wx_qcode'],
            'account' => $sysUserOne['account'],
            'nickname' => $sysUserOne['nickname'],
            'email' => $sysUserOne['email'],
            'mobile' => $sysUserOne['mobile'],
            'menuInfo' => $menuInfo,
            'userAuth' => $userAuth,
            'clearInfo' => [],
        ];
    }

    /**
     * 添加/修改
     * @param array $data
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function roleUpdate(array $data): array
    {
        $code = 0;
        $msg = 'success';
        //当前操作人id
        $creator_id = adminInfo('id');
        $rolePermissionsModel = new SysRolePermissionsModel();

        //验证部门名称重复
        //id存在，修改，排除查找
        $whereNotId = [];
        if (!empty($data['id'])) {
            $whereNotId = [$data['id']];
        }

        //手机号不能重复
        $whereOrOne = 0;
        if (!empty($data['role_name'])) {
            $whereOrOne = $data['role_name'];
        }

        $roleTran = SysRoleModel::getOneByDeWeight($whereNotId, $whereOrOne);

        if (!empty($roleTran)) {
            return [1003, '部门名称，重复！'];

        }

        //获取部门、权限
        $permission_id = array();
        if (isset($data['department_id'])) {
            unset($data['department_id']);
        }

        if (isset($data['permission_id'])) {
            $permission_id['permission_id'] = $data['permission_id'];
            unset($data['permission_id']);
        }


        if (isset($data['id']) && !empty($data['id'])) {
            //获取当前操作数据
            try {
                $oneArr = $this->one($data['id']);
            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
                return [$code, $msg];
            }

            //数据验证（删除数据不能修改）
            if (empty($oneArr)) {
                return [1023, '数据不存在'];
            }

            try {
                if (isset($permission_id['permission_id'])) {
                    $rolePermissionsModel->deleteRolePermissions(['role_id' => $data['id']]);
                    //修改权限
                    $rolePermissionsModel->insertRolePermissions($this->manageRoles($permission_id, $data['id'], 'permission_id', 'role_id'));
                }

                //修改
                $id = $data['id'];
                unset($data['id']);
                $data['updated_at'] = time();
                $data['creator_id'] = $creator_id;
                $data['creator_name'] = adminInfo('nickname');
                SysRoleModel::query()->where('id', $id)->update($data);
            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
            }
        } else {
            //新增
            try {
                $data['created_at'] = time();
                $data['updated_at'] = time();
                $data['creator_id'] = $creator_id;
                $data['creator_name'] = adminInfo('nickname');

                $data['id'] = SysRoleModel::query()->insertGetId($data);

                if (isset($permission_id['permission_id']) && !empty($permission_id['permission_id'])) {
                    //修改用户岗位
                    $rolePermissionsModel->insertRolePermissions($this->manageRoles($permission_id, $data['id'], 'permission_id', 'role_id'));
                }
            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
            }
        }
        return [$code, $msg];
    }

    /**
     * 获取一条数据
     * @param string $id
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function one(string $id): array
    {
        //刷选条件
        $where = array();
        $where['deleted_at'] = 0;
        $where['id'] = $id;

        $list = SysRoleModel::query()
            ->where($where)
            ->paginate(request()->get('limit', 30));
        return $list ? $list->toArray() : [];
    }

    /**
     * 删除
     * @param array $id
     * @param array $data
     * @return array|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function roleDelete(array $id, array $data): ?array
    {
        $code = 0;
        $msg = 'success';

        if (!empty($id)) {
            //获取当前操作数据
            try {
                $oneArr = SysRoleModel::query()
                    ->where(['deleted_at' => 0])
                    ->whereIn('id', $id)
                    ->get();

                $parentArr = SysRoleModel::query()
                    ->where(['deleted_at' => 0])
                    ->whereIn('parent_id', $id)
                    ->get();

                //获取角色权限关联表
                $roleUsers = SysUserRoleModel::query()
                    ->where(['role_id' => $id])
                    ->get();
            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
                return [$code, $msg];
            }

            $oneArr = $oneArr ? $oneArr->toArray() : [];
            $parentArr = $parentArr ? $parentArr->toArray() : [];
            $roleUsers = $roleUsers ? $roleUsers->toArray() : [];

            if (!empty($parentArr)) {
                return [1025, '子集不为空'];
            }

            //数据验证（删除数据不能修改）
            if (empty($oneArr)) {
                return [1026, '数据不存在'];
            }

            //验证表关联关系 是否有数据 有数据不予修改
            if (!empty($roleUsers)) {
                return [1027, '现有角色已绑定用户，不能删除'];
            }

            $rolePermissionsModel = new SysRolePermissionsModel();
            $userRoleModel = new SysUserRoleModel();
            $data['creator_id'] = adminInfo('id');
            $data['creator_name'] = adminInfo('nickname');

            //修改
            try {
                SysRoleModel::query()
                    ->whereIn('id', $id)
                    ->update($data);

                //删除关联表相关数据
                $userRoleModel->deleteUserRole(['role_id' => $id]);
                $rolePermissionsModel->deleteRolePermissions(['role_id' => $id]);

            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
            }
        } else {
            return [1028, '数据不存在'];
        }

        return [$code, $msg];

    }

    /**
     * 获取状态正常的用户(不带分页)
     * @param array $data
     * @return array
     */
    public function whole(array $data = []): array
    {
        $where = array();
        $where[] = ['deleted_at', '=', 0];
        //过滤删选条件-状态
        if (isset($data['status']) && ($data['status'] == '1' || $data['status'] == '0')) {
            $where[] = ['status', '=', $data['status']];
        }

        //过滤删选条件-1 菜单 2 按钮 3 浏览 4 导航
        if (isset($data['type']) && !empty($data['type'])) {
            $where[] = ['type', '=', $data['type']];
        }

        //过滤删选条件-菜单名称
        if (isset($data['permission_name']) && !empty($data['permission_name'])) {
            $where[] = ['permission_name', 'like', '%' . $data['permission_name'] . '%'];
        }

        $query = SysPermissionsModel::query();
        $query->select('id', 'permission_name as title', 'parent_id', 'tag', 'icon', 'target', 'component_name', 'component', 'path', 'sort', 'type', 'redirect', 'sidebar', 'status', 'creator_name');
        $query->where($where);

        //过滤删选条件-创建时间
        if (isset($data['created_at']) && $data['created_at']) {
            $created_at = explode(' - ', $data['created_at']);
            $query->whereBetween('created_at', [strtotime($created_at[0]), strtotime($created_at[1])]);
        }

        $query->orderBy('sort');
        $list = $query->get();
        return $list ? $list->toArray() : [];

    }

    /**
     * 获取权限架构
     * @param $menuList
     * @return array|null
     */
    public function getPermissionsListByPermissionsIdsLevel($menuList): ?array
    {
        $menuInfo = [];
        //处理菜单，按钮等数据

        //按钮权限集合
        $buttonInfo = [];
        foreach ($menuList as $value) {
            $value = (array)$value;
            if ($value['type'] != '1') {
                $buttonInfo[] = $value;
            }
            if ($value['type'] == '1') {
                $menuInfo[] = $value;
            }
        }
        foreach ($menuInfo as &$menu) {
            $menu['auth'] = [];
            foreach ($buttonInfo as $button) {
                if ($button['parent_id'] == $menu['id']) {
                    $menu['auth'][] = $button;
                }
            }
        }
        return makeTree($menuInfo, 'id', 'parent_id', 'children');
    }

    /**
     * 用户列表
     * @param array $data
     * @param string $switch
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function userAll(array $data = [], string $switch = 'on'): array
    {
        $where = array();
        $where[] = ['info_sys_users.deleted_at', '=', 0];
        //过滤删选条件-员工名称
        if (!empty($data['nickname'])) {
            $where[] = ['info_sys_users.nickname', 'like', '%' . $data['nickname'] . '%'];
        }

        //过滤删选条件-员工工号
        if (!empty($data['job_num'])) {
            $where[] = ['info_sys_users.job_num', '=', $data['job_num']];
        }

        //过滤删选条件-状态
        if (isset($data['status'])) {
            $where[] = ['info_sys_users.status', '=', $data['status'] ?? 1];
        }

        //过滤删选条件-维护人
        $whereIn = [];
        if (!empty($data['type'])) {
            $whereIn = ['info_sys_roles.style', [1,3]];
        }

        $query = SysUserModel::query()
            ->select(['info_sys_users.*', 'info_sys_roles.role_name', 'info_sys_roles.id as role_id'])
            ->leftJoin('info_sys_user_has_roles', 'info_sys_user_has_roles.uid', '=', 'info_sys_users.id')
            ->leftJoin('info_sys_roles', 'info_sys_user_has_roles.role_id', '=', 'info_sys_roles.id')
            ->with('area_province')
            ->with('area_city')
            ->with('area_district');

        $query->where($where);

        if (!empty($whereIn)){
            $query->whereIn($whereIn[0], $whereIn[1]);
        }

        //过滤删选条件-创建时间
        if (isset($data['created_at']) && $data['created_at']) {
            $created_at = explode(' - ', $data['created_at']);
            $query->whereBetween('info_sys_users.created_at', [strtotime($created_at[0]), strtotime($created_at[1]) + 86400]);
        }

        $list = $query->paginate(request()->get('limit', 30));

        $list = $list ? $list->toArray() : [];
        foreach ($list['data'] as &$value) {
            if (!empty($value['mobile'])) {
                $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            }

            //生成省市区的地址
            $value['area_msg'] = '';
            if (!empty($value['area_province'][0]['name'])){
                $value['area_msg'] .= '-' . $value['area_province'][0]['name'];
            }

            if (!empty($value['area_city'][0]['name'])){
                $value['area_msg'] .= '-' . $value['area_city'][0]['name'];
            }

            if (!empty($value['area_district'][0]['name'])){
                $value['area_msg'] .= '-' . $value['area_district'][0]['name'];
            }

            $value['area_msg'] = trim($value['area_msg'], '-');

            unset($value['area_province'], $value['area_city'], $value['area_district'], $value['password'], $value['updated_at'], $value['deleted_at'], $value['updated_operator_id']);
        }
        return FormatBase::listData($list);
    }

    /**
     * 用户删除
     * @param array $id
     * @param array $data
     * @return array|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function userDelete(array $id, array $data): ?array
    {
        $code = 0;
        $msg = 'success';

        if (!empty($id)) {
            //获取当前操作数据
            try {
                $oneArr = SysUserModel::query()
                    ->where(['deleted_at' => 0])
                    ->whereIn('id', $id)
                    ->get();
            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
                return [$code, $msg];
            }

            //数据验证（删除数据不能修改）
            if (empty($oneArr)) {
                return [1030, '数据不存在'];
            }

            $userRoleModel = new SysUserRoleModel();
            //获取操作人
            $data['updated_at'] = time();
            $data['updated_operator_id'] = adminInfo('id');
            $data['updated_operator_name'] = adminInfo('nickname');

            //修改
            try {
                SysUserModel::query()
                    ->whereIn('id', $id)
                    ->update($data);
                //删除关联表相关数据
                $userRoleModel->deleteUserRole(['uid' => $id]);

            } catch (Exception $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();
            }
        } else {
            return [1030, '数据不存在'];
        }

        return [$code, $msg];

    }

    /**
     * 商店列表
     * @param array $data
     * @return array
     */
    public function handleGoodsResponse(array $data = []): array
    {
        $temp = [];
        foreach ($data['data'] as $value) {
            unset($tempSons);
            $tempSons['original_img'] = $value['original_img'] ?? '';

            if ($value['type'] == 1 || $value['type'] == 3) {
                //商品、服务
                //商品名称 一对一with写法
                if (!empty($value['goods_name'])) {
                    $tempSons['goods_name'] = $value['goods_name'];
                } else {
                    $tempSons['goods_name'] = '';
                }

                //食物重量/服务时常 一对一with写法
                if (!empty($value['weight'])) {
                    $tempSons['weight'] = $value['weight'];
                } else {
                    $tempSons['weight'] = '';
                }

                //重量类型  1：g（克）  2：kg（千克） 3：h（小时） 一对一with写法
                if (!empty($value['weight_type'])) {
                    $tempSons['weight_type'] = $value['weight_type'];
                } else {
                    $tempSons['weight_type'] = '';
                }

                if (!empty($value['use_num'])) {
                    //商品数
                    $tempSons['num'] = $value['use_num'];
                } else {
                    $tempSons['num'] = 1;

                }

                $temp[$value['id']][] = $tempSons;
            } elseif ($value['type'] == 2) {
                //套餐
                //json数组
                $tempSons = json_decode($value['weight_json'], true);

                foreach ($tempSons as $vSons) {
                    $vSons['original_img'] = $value['original_img'] ?? '';
                    $temp[$value['id']][] = $vSons;

                }

            }


        }

        return $temp;
    }

    /**
     * 消息通知-列表
     * @param array $params
     * @return array
     */
    public function sysMessage(array $params = []): array
    {
        $where[] = ['deleted_at', '=', 0];
        if (!empty($params['content'])) {
            $where[] = ['content', 'like', '%' . $params['content'] . '%'];
        }

        $res = SysMessageModel::getPage($where, $params['limit'] ?? 15);

        foreach ($res['data'] as &$value) {
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            if (!empty($value['user_msg'][0]['nickname'])) {
                if (!empty($value['user_msg'][0]['mobile'])) {
                    $value['user_msg'] = $value['user_msg'][0]['nickname'] . '（' . $value['user_msg'][0]['mobile'] . '）';

                } else {
                    $value['user_msg'] = $value['user_msg'][0]['nickname'];

                }

            } else {
                $value['user_msg'] = '';
            }
        }

        return FormatBase::listData($res);
    }

    public function handleUserStatic($params):array
    {
        $where = [];
        //'number', 'id', 'nickname', 'status', 'style'
        if (isset($params['number']) && !empty($params['number'])) {
            $where[] = ['number', 'like', '%' . $params['number'] . '%'];
        }

        if (isset($params['nickname']) && !empty($params['nickname'])) {
            $where[] = ['nickname', 'like', '%' . $params['nickname'] . '%'];
        }

        if (!empty($params['id'])){
            $where[] = ['id', '=', $params['id']];
        }

        if (!empty($params['mobile'])){
            $where[] = ['mobile', '=', $params['mobile']];
        }

        if (!empty($params['area_province_id'])){
            $where[] = ['area_province_id', '=', $params['area_province_id']];
        }

        if (!empty($params['area_city_id'])){
            $where[] = ['area_city_id', '=', $params['area_city_id']];
        }

        if (!empty($params['area_district_id'])){
            $where[] = ['area_district_id', '=', $params['area_district_id']];
        }

        if (!empty($params['status'])){
            $where[] = ['status', '=', $params['status']];
        }

        if (!empty($params['style'])){
            //1完善 2不完善
            if ($params['style'] == 1){
                $where[] = ['number', '<>', ''];

            }else{
                $where[] = ['number', '=', ''];

            }
        }

        return $where;
    }

}
